package com.sdy.kzyy.pc.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.EncodeUtil;
import com.sdy.kzyy.biz.constants.RedisConstants;
import com.sdy.kzyy.biz.model.Manager;
import com.sdy.kzyy.biz.model.Store;
import com.sdy.kzyy.biz.service.ManagerService;
import com.sdy.kzyy.biz.service.StoreService;
import com.sdy.kzyy.biz.vo.WebUserInfoVO;
import com.sdy.kzyy.pc.util.Constants;
import com.sdy.mvc.controller.BaseController;
import com.sdy.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyPair;
import java.util.Base64;

/**
 * Created by zzq on 2019/1/10.
 */
@Slf4j
@RestController
@RequestMapping("/index")
@Api(tags = "基础信息接口")
public class IndexController extends BaseController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private StoreService storeService;

    @GetMapping("/publicKey")
    public Response publicKey(HttpServletRequest request) throws Exception {
        KeyPair keyPair = EncodeUtil.rsaGenKeyPair();
        String publicKeyStr = new String(Base64.getEncoder().encode(keyPair.getPublic().getEncoded()));
        redisService.set(RedisConstants.REDIS_PREFIX + "privateKey_" + getUserId(request), Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()));
        return Response.success(publicKeyStr);
    }

    @GetMapping("/webUserInfo")
    @ApiOperation(value = "获取当前用户基本信息")
    public Response<WebUserInfoVO> webUserInfo(HttpServletRequest request) {
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Manager manager = managerService.getById(userId);
        if (manager == null) {
            return Response.error();
        }
        String storeCode = null;
        String name = null;
        Store one = storeService.getOne(Wrappers.<Store>lambdaQuery().eq(Store::getStoreCode, manager.getStoreCode()));
        if (one != null) {
            storeCode = one.getStoreCode();
            name = one.getName();
        }
        WebUserInfoVO userInfoVO = new WebUserInfoVO();
        userInfoVO.setName(manager.getName()).setStoreCode(storeCode).setStoreName(name).setId(userId);
        return Response.success(userInfoVO);
    }
}
